import frappe
from frappe import _
from frappe.utils import cint

@frappe.whitelist()
def get_sidebar_config():
    """
    获取侧边栏配置信息
    
    Returns:
        dict: 侧边栏配置
    """
    try:
        user = frappe.session.user
        
        # 获取用户偏好设置
        hide_right_sidebar = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": "hide_right_sidebar"
            },
            "preference_value"
        ) or 0
        
        return {
            "success": True,
            "config": {
                "hide_right_sidebar": cint(hide_right_sidebar),
                "sidebar_position": "right",  # 默认右侧
                "animation_duration": 300,
                "responsive_breakpoint": 768
            }
        }
    except Exception as e:
        frappe.log_error(f"获取侧边栏配置失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def set_sidebar_hidden(hidden=0, user=None):
    """
    设置侧边栏隐藏状态
    
    Args:
        hidden (bool): 是否隐藏
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 操作结果
    """
    try:
        if not user:
            user = frappe.session.user
        
        # 使用User Preference文档类型存储设置
        preference_name = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": "hide_right_sidebar"
            },
            "name"
        )
        
        if preference_name:
            frappe.db.set_value(
                "User Preference",
                preference_name,
                "preference_value",
                "1" if hidden else "0"
            )
        else:
            doc = frappe.get_doc({
                "doctype": "User Preference",
                "user": user,
                "preference_key": "hide_right_sidebar",
                "preference_value": "1" if hidden else "0",
                "description": "隐藏右侧边栏"
            })
            doc.insert()
        
        frappe.db.commit()
        
        return {
            "success": True,
            "message": "侧边栏设置已更新",
            "hidden": bool(hidden),
            "user": user
        }
    except Exception as e:
        frappe.log_error(f"设置侧边栏隐藏状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def toggle_sidebar(user=None):
    """
    切换侧边栏隐藏/显示状态
    
    Args:
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 操作结果
    """
    try:
        if not user:
            user = frappe.session.user
        
        # 获取当前状态
        current_state = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": "hide_right_sidebar"
            },
            "preference_value"
        ) or 0
        
        # 切换状态
        new_hidden = not cint(current_state)
        
        # 保存新状态
        result = set_sidebar_hidden(new_hidden, user)
        
        if result.get("success"):
            result["previous_state"] = bool(current_state)
            result["new_state"] = new_hidden
        
        return result
    except Exception as e:
        frappe.log_error(f"切换侧边栏状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def get_sidebar_state(user=None):
    """
    获取当前侧边栏状态
    
    Args:
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 侧边栏状态
    """
    try:
        if not user:
            user = frappe.session.user
        
        # 获取当前状态
        hide_sidebar = frappe.get_value(
            "User Preference",
            {
                "user": user,
                "preference_key": "hide_right_sidebar"
            },
            "preference_value"
        ) or 0
        
        return {
            "success": True,
            "hidden": bool(cint(hide_sidebar)),
            "user": user,
            "last_updated": frappe.utils.now()
        }
    except Exception as e:
        frappe.log_error(f"获取侧边栏状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def reset_sidebar_preferences(user=None):
    """
    重置侧边栏偏好设置
    
    Args:
        user (str, optional): 用户名，默认为当前用户
        
    Returns:
        dict: 操作结果
    """
    try:
        if not user:
            user = frappe.session.user
        
        # 删除所有相关的用户偏好设置
        frappe.db.delete(
            "User Preference",
            {
                "user": user,
                "preference_key": ["in", ["hide_right_sidebar", "sidebar_position"]]
            }
        )
        
        frappe.db.commit()
        
        return {
            "success": True,
            "message": "侧边栏偏好设置已重置",
            "user": user
        }
    except Exception as e:
        frappe.log_error(f"重置侧边栏偏好设置失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }